package thread;

/**
 * 并发安全问题；
 */
public class Demo06Sync {
    static boolean success1;//微信转账是否成功；
    static boolean success2;//ATM机取款是否成功；

    public static void main(String[] args) {
        Bank bank = new Bank();
        int sum=0;
        while (true) {
            //微信转账的线程
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };
            //ATM机群款两万
            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            try {
                //让主线程卡住，阻塞50毫秒，等待t1和t2两个线程执行完成；
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //判断
            if (success1 && success2) {
                System.out.println("两种方式同时取款成功...");
                break;
            } else {
                //如果没有成功，就重新把钱存起来,初始化一下数据
                bank.saveAccount(20000);
                success1 = false;
                success2 = false;
                sum++;
                System.out.println(sum);
            }
        }

    }
}

class Bank {
    private int account = 20000;//银行卡余额

    /*
    取钱方法
    */
    public synchronized boolean getMoney(int money) {
        //1.查余额
        int account = getAccount();
        //2.判断取款金额是否小于余额；
        if (money <= account) {
            account = account - money;//计算新的余额
            saveAccount(account);//更新余额
            return true;
        }
        return false;
    }

    /**
     *
     */
    public int getAccount() {
        return account;
    }

    /**
     *
     */
    public void saveAccount(int account) {
        this.account = account;
    }
}